<template>
  <div class="container">
    <a-upload
      name="avatar"
      listType="picture-card"
      class="avatar-uploader"
      :showUploadList="false"
      :beforeUpload="beforeUpload"
      @change="handleChange"
    >
      <img class="img" v-if="imageUrl" :src="imageUrl" alt="avatar" />
      <div v-else>
        <a-icon :type="loading ? 'loading' : 'plus'" />
        <div class="ant-upload-text">Upload</div>
      </div>
    </a-upload>

    <a-form :form="form" @submit="handleSubmit">
      <a-form-item>
        <a-input
          placeholder="用户名"
          v-decorator="['user_name', { rules: [{ required: true, message: '请填写用户名!' }] }]"
        />
      </a-form-item>
      <a-form-item>
        <a-input
          placeholder="年龄"
          v-decorator="['age', { rules: [{ required: true, message: '请填写年龄!' }] }]"
        />
      </a-form-item>
      <a-form-item>
        <a-button type="primary" html-type="submit">提交</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script>
function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener("load", () => callback(reader.result));
  reader.readAsDataURL(img);
}

export default {
  data() {
    return {
      loading: false,
      imageUrl: "",
      form: this.$form.createForm(this, { name: "coordinated" })
    };
  },
  methods: {
    handleSubmit(e) {
      e.preventDefault();
      this.form.validateFields((err, values) => {
        if (!err) {
          const obj = {
            img: this.imageUrl,
            ...values
          };

          fetch("/api/add", {
            method: "post",
            headers: { "Content-type": "application/json" },
            body: JSON.stringify(obj)
          })
            .then(res => res.json())
            .then(res => {
              if (res.status) {
                this.$message.success("文章发布成功");
                this.$router.push("/lists");
              } else {
                this.$message.error(res);
              }
            });

          console.log("Received values of form: ", obj);
        }
      });
    },
    handleChange(info) {
      console.log("info", info);
      if (info.file.status === "uploading") {
        this.loading = true;
        return;
      }
      if (info.file.status === "done") {
        // Get this url from response in real world.
        getBase64(info.file.originFileObj, imageUrl => {
          this.imageUrl = imageUrl;
          this.loading = false;

          console.log("this.imageUrl", this.imageUrl);
        });
      }
    },
    beforeUpload(file) {
      const isJPG = file.type === "image/jpeg";
      if (!isJPG) {
        this.$message.error("You can only upload JPG file!");
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("Image must smaller than 2MB!");
      }
      return isJPG && isLt2M;
    },
    handleUpload() {
      const { fileList } = this;
      const formData = new FormData();
      fileList.forEach(file => {
        formData.append("files[]", file);
      });
      this.uploading = true;

      // You can use any AJAX library you like
      reqwest({
        url: "https://www.mocky.io/v2/5cc8019d300000980a055e76",
        method: "post",
        processData: false,
        data: formData,
        success: () => {
          this.fileList = [];
          this.uploading = false;
          this.$message.success("upload successfully.");
        },
        error: () => {
          this.uploading = false;
          this.$message.error("upload failed.");
        }
      });
    }
  }
};
</script>

<style>
.container {
  background-color: #fff;
}
.container .img {
  width: 300px;
}
</style>>
